# Create your views here.
from rest_framework import status
from rest_framework.filters import OrderingFilter
from rest_framework.generics import ListAPIView, CreateAPIView, RetrieveAPIView, GenericAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

from complains.models import Complain, Comment
from complains.serializers import SendComplainSerializer,  \
    ComplainLikeserizlizer, ComplainDetailSerializer, ComplainCommentSerializer, ComplainListSerializer
from complains.utils.pagination import StandardResultsSetPagination


class ComplainListView(ListAPIView):
    """吐槽列表页展示"""
    queryset = Complain.objects.all()
    serializer_class = ComplainListSerializer
    pagination_class = StandardResultsSetPagination
    filter_backends = (OrderingFilter,)
    ordering_fields = ('create_time',)


class ComplainDetailView(GenericAPIView):
    """
       吐槽详情页展示
       """
    queryset = Complain.objects.all()
    serializer_class = ComplainDetailSerializer

    def get(self, request, pk):
        spit = self.get_object()
        # print(spit)
        s = self.get_serializer(spit)
        return Response(s.data)


class ComplainCommentView(GenericAPIView):
    queryset = Comment.objects.all()
    serializer_class = ComplainCommentSerializer


class SendComplainView(CreateAPIView):
    # permission_classes = [IsAuthenticated]
    serializer_class = SendComplainSerializer


class ComplainLike(RetrieveAPIView):
    """
    吐槽点赞
    必须是登陆的的用户才能点赞
    获取吐槽id   Complain_id
    获取点赞动作
    如果action=add   吐槽点赞数+1
    如果action=remove 吐槽点赞数-1
    """
    permission_classes = [IsAuthenticated]
    serializer_class = ComplainLikeserizlizer

    def put(self, request):
        serializer = self.get_serializer(data=request.data)
        serializer.is_vaild(raise_exception=True)

        id = serializer.validated_data['id']
        action = request.data['action']



class ComplainCommentLikeView(APIView):
    """
    吐槽模块内的评论点赞
    """
    permission_classes = [IsAuthenticated]

    def post(self, request, pk):
        user = request.user_id
        user_comment = Comment.objects.get(user_id=user.id)
        if user_comment:
            return Response({"message": "您已为此条评论点赞过"})
        else:
            comment_like = Comment()
            comment_like.user = user.id
            comment_like.comment = pk
            comment_like.save()
            comment = Comment()
            comment.liked_count += 1
            comment.save()
        data = {
            "liked_count": Comment.comment_like_count,
            "message": "点赞成功"
        }
        return Response(data=data, status=status.HTTP_200_OK)
